'use client';

import { useQuery } from '@tanstack/react-query';
import {
  queryAllPost,
  queryChildReplyStatistics,
  queryCommentStatistics,
  queryParentReplyStatistics,
  queryReplyStatistics,
  searchPost,
} from '@/services/api';
import type {
  IChildReplyStatistics,
  ICommentStatistics,
  IPagination,
  IParentReplyStatistics,
  IPost,
  IQueryParams,
  IReplyStatistics,
} from '@/interfaces';
import Box from '@/app/[locale]/admin/common/box';
import PostName from '@/app/[locale]/common/post/name';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import Pagination from '@/app/[locale]/admin/common/pagination';
import { type ChangeEvent, useState } from 'react';
import { useRouter } from 'next/navigation';
import Alert from '@/app/[locale]/alert/alert';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function ReplyAdminPage(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IPagination<IPost>;
    translatedFields: PrefixedTTranslatedFields<'replyAdminPage'>;
  },
) {
  const [searchName, setSearchName] = useState('');
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
  });
  const router = useRouter();

  const queryCommentStatisticsQuery = useQuery(
    ['/forum', '/comments', '/statistics'],
    async () => {
      return (await queryCommentStatistics()) as ICommentStatistics;
    },
  );
  const queryReplyStatisticsQuery = useQuery(
    ['/forum', '/replies', '/statistics'],
    async () => {
      return (await queryReplyStatistics()) as IReplyStatistics;
    },
  );
  const queryParentReplyStatisticsQuery = useQuery(
    ['/forum', '/replies', '/statistics', '/parent'],
    async () => {
      return (await queryParentReplyStatistics()) as IParentReplyStatistics;
    },
  );
  const queryChildReplyStatisticsQuery = useQuery(
    ['/forum', '/replies', '/statistics', '/child'],
    async () => {
      return (await queryChildReplyStatistics()) as IChildReplyStatistics;
    },
  );
  const queryAllPostQuery = useQuery(
    ['/forum', '/posts', params, searchName],
    async (context) => {
      if (searchName) {
        return (await searchPost({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<IPost>;
      } else {
        return (await queryAllPost({
          query: context.queryKey[2] as any,
        })) as IPagination<IPost>;
      }
    },
    {
      keepPreviousData: true,
      initialData: source,
    },
  );

  function onClickDetail(item: IPost) {
    router.push(`reply/comment?pid=${item.id}`);
  }

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value.trim();
    setSearchName(value.toLowerCase());
  }

  function onClickPrevious() {
    const data = queryAllPostQuery.data;
    if (!data) {
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllPostQuery.data;
    if (!data) {
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  return (
    <div className="row g-4">
      <div className="col-12">
        <Box>
          <div className="row">
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.comment}
                  </h6>
                  <h5 className="card-title">
                    {queryCommentStatisticsQuery.data &&
                      queryCommentStatisticsQuery.data.count}

                    {queryCommentStatisticsQuery.isError && (
                      <Alert
                        message={queryCommentStatisticsQuery.error}
                        type="error"
                      />
                    )}

                    {queryCommentStatisticsQuery.isLoading && <Spinner />}
                  </h5>
                </div>
              </div>
            </div>
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.reply}
                  </h6>
                  <h5 className="card-title">
                    {queryReplyStatisticsQuery.data &&
                      queryReplyStatisticsQuery.data.count}

                    {queryReplyStatisticsQuery.isError && (
                      <Alert
                        message={queryReplyStatisticsQuery.error}
                        type="error"
                      />
                    )}

                    {queryReplyStatisticsQuery.isLoading && <Spinner />}
                  </h5>
                </div>
              </div>
            </div>
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.reply2}
                  </h6>
                  <h5 className="card-title">
                    {queryParentReplyStatisticsQuery.data &&
                      queryParentReplyStatisticsQuery.data.count}

                    {queryParentReplyStatisticsQuery.isError && (
                      <Alert
                        message={queryParentReplyStatisticsQuery.error}
                        type="error"
                      />
                    )}

                    {queryParentReplyStatisticsQuery.isLoading && <Spinner />}
                  </h5>
                </div>
              </div>
            </div>
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.reply3}
                  </h6>
                  <h5 className="card-title">
                    {queryChildReplyStatisticsQuery.data &&
                      queryChildReplyStatisticsQuery.data.count}

                    {queryChildReplyStatisticsQuery.isError && (
                      <Alert
                        message={queryChildReplyStatisticsQuery.error}
                        type="error"
                      />
                    )}

                    {queryChildReplyStatisticsQuery.isLoading && <Spinner />}
                  </h5>
                </div>
              </div>
            </div>
          </div>
        </Box>
      </div>
      <div className="col">
        <Box>
          <div className="card">
            <div className="card-header bg-transparent">
              <div className="row row-cols-auto justify-content-between g-2">
                <div className="col">
                  <div className="input-group">
                    <span className="input-group-text">
                      <i className="bi bi-search"></i>
                    </span>
                    <input
                      onChange={onChangeSearch}
                      type="search"
                      className="form-control"
                      placeholder={translatedFields.tip.searchPlaceholder}
                    />
                  </div>
                </div>
                <div className="col"></div>
              </div>
            </div>
            <div className="card-body vstack gap-4">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <tbody>
                    {queryAllPostQuery.data.content.map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            <div className="d-flex gap-2">
                              <PostName
                                item={item}
                                isTable
                                isFwSemibold={false}
                              />
                              <span>(ID. {item.id})</span>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {queryAllPostQuery.data.content.length === 0 && <Nodata />}

              <Pagination
                isShow={queryAllPostQuery.data.pageable.pages > 0}
                onPrevious={onClickPrevious}
                onNext={onClickNext}
                isPrevious={queryAllPostQuery.data.pageable.previous}
                isNext={queryAllPostQuery.data.pageable.next}
                translatedFields={translatedFields.pagination}
              />
            </div>
          </div>
        </Box>
      </div>
    </div>
  );
}
